﻿using System;
using System.Web;
using System.Web.Services;
using System.IO;
using MaLu.Common;
using MaLu.BusiLogic;
using MaLu.Data;

namespace MaluJg.web.Common
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UploadFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //简单示例，如果需要存文件名称，大小之类的请自己写了
                string oFileName = context.Request["Filename"];
                FileInfo ofile = new FileInfo(oFileName);
                string folder = context.Request["folder"];
                if (context.Request.Files.Count > 0)
                {
                    if (folder.StartsWith("/")) //由于上传控件如果不在最开始加上"/"，会自动带上html文件相对路径，为了定义不上传到站点目录而是上传到web.config中指定的目录，加了这个操作，这个可以根据要求自行处理
                        folder = folder.Substring(1);
                    string serverFolder = Path.Combine(Config.UploadFolder, folder);
                    if (!Directory.Exists(serverFolder))
                        Directory.CreateDirectory(serverFolder);
                    string currentFileName = Guid.NewGuid() + ofile.Extension;
                    context.Request.Files[0].SaveAs(Path.Combine(serverFolder, currentFileName));
                    Guid fileid = Guid.NewGuid();
                    IDbProvider provider = ProviderManager.Factory.CreateDbProvider();
                    provider.Open();

                    BLAttach.SaveAttach(provider, fileid, oFileName, currentFileName, Path.Combine(serverFolder, currentFileName), 0);
                    context.Response.Write(fileid.ToString());
                }
                else
                    context.Response.Write("0");
            }
            catch
            {
                context.Response.Write("0");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
